/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 ManagedServerListenerTester.hpp. Created on: 18.09.2009 15:30:09
 */

#ifndef MANAGEDSERVERLISTENERTESTER_HPP_
#define MANAGEDSERVERLISTENERTESTER_HPP_

#include "cpputils/TestUtils.hpp"
#include "ManagedConnectionListenerTester.hpp"
#include "smartobjects/network/IManagedServerListener.hpp"

class ManagedServerListenerTester : public IManagedServerListener {
public:
	typedef boost::shared_ptr<ManagedServerListenerTester> SharedPtr;
	typedef std::list<IManagedConnection*> Connections;
	typedef std::list<ConnectionHandler*> Handlers;

public:
	ManagedServerListenerTester();
	virtual ~ManagedServerListenerTester();

	virtual void onConnected(IManagedConnection*) throw();
	virtual void onConnected(ConnectionHandler*) throw();

	void reset();

	bool isAccepted();
	int getLastErrorCode();
	void closeConnections();

	Connections& getConnections();
	ManagedConnectionListenerTester& getConnectionListener();

	boost::recursive_mutex& getMonitor();
	boost::recursive_mutex& getMonitorPerHandler();
	void waitForAnyEvent(boost::recursive_mutex::scoped_lock& oLock, const std::string& sLocation="Unknown location");
	void waitForAnyEventPerHandler(boost::recursive_mutex::scoped_lock& oLock, const std::string& sLocation="Unknown location");

	Handlers& getLastHandlers();

protected:
	void notifyWaiter();
	void notifyWaiterPerHandler();
	void addLastHandler(ConnectionHandler *poHandler);

private:
	bool m_bAccepted;
	int m_nLastErrorCode;
	boost::condition m_evAwait;
	boost::recursive_mutex m_mxMonitor;

	boost::condition m_evAwaitPerHandler;
	boost::recursive_mutex m_mxMonitorPerHandler;

	/**
	 * Listener's connection
	 */
	Connections m_aConnections;
	boost::recursive_mutex m_mxConnections;

	ManagedConnectionListenerTester m_oConnectionListener;
	Handlers m_aHandlers;
};

#endif /* MANAGEDSERVERLISTENERTESTER_HPP_ */
